package com.faithbj.controller.statistics;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.faithbj.common.model.Region;
import com.faithbj.common.model.User;
import com.faithbj.common.utils.DateUtils;
import com.faithbj.constant.Constant;
import com.faithbj.model.conditions.CheckFamilyStatResult;
import com.faithbj.model.conditions.CompareStatData;
import com.faithbj.model.conditions.CompareStatResult;
import com.faithbj.model.conditions.ReportStatResult;
import com.faithbj.model.conditions.StreetCompareStatData;
import com.faithbj.model.conditions.StreetFamilyStatData;
import com.faithbj.model.conditions.StreetReportData;
import com.faithbj.model.conditions.StreetWorkInfoData;
import com.faithbj.model.conditions.WorkInfoStatResult;
import com.faithbj.process.State;
import com.faithbj.process.stats.JbpmStatsService;
import com.faithbj.service.statistics.CheckBusinessStatService;
import com.faithbj.service.statistics.TestJbpmStatsService;
import com.faithbj.support.fp.Tuple4;
import com.faithbj.utils.StatisticsExcelUtil;

/**
 * 核对业务统计
 * @author m
 * @date   2012-06-18
 */
@Controller
@SessionAttributes("resultList")
@RequestMapping("/checkBusinessStat")
public class CheckBusinessStatController extends StatBaseController {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1663498356901706673L;
	@Resource
	private CheckBusinessStatService checkBusinessStatService;
//	@Resource 因jbpm还未实现，暂时注释掉
	private JbpmStatsService jbpmStatService;
	@Resource
	private TestJbpmStatsService testJbpmStatsService;
	
	/**核对家庭统计*/
	@RequestMapping("/checkFamilyStat")
	public String checkFamilyStat(HttpServletRequest request, ModelMap model) {		
		//初始化区县列表
		this.initCountryRegionList();
		
		String acceptStartTime = request.getParameter("acceptStartTime");
		String acceptEndTime = request.getParameter("acceptEndTime");
		String countiesRegionId = request.getParameter("countiesRegionId");
		String streetRegionId = request.getParameter("streetRegionId");
		Date from = null;
		Date to = null;
		if(StringUtils.isNotBlank(acceptStartTime)){
			from = DateUtils.getStringToDate(acceptStartTime, DateUtils.DateFormatDefault);
		}
		if(StringUtils.isNotBlank(acceptEndTime)) {
			to = DateUtils.getStringToDate(acceptEndTime, DateUtils.DateFormatDefault);
		}
		
		List<Region> countryRegionList = getCountryRegionList(countiesRegionId, streetRegionId);
		
		List<CheckFamilyStatResult> result =new ArrayList<CheckFamilyStatResult>();
		if(countryRegionList != null){
			result = checkBusinessStatService.getCheckFamilyResult(from, to, countryRegionList);
		}
		
		model.put("resultList", result);
		model.put("countryRegionList", this.countryRegionList);
		return "/analysis/checkHomeStatistics";
	}
	
	/**交换比对统计 */
	@RequestMapping("/compareStat")
	public String compareStat(HttpServletRequest request, ModelMap model) {
		//初始化区县列表
		this.initCountryRegionList();
		
		String acceptStartTime = request.getParameter("acceptStartTime");
		String acceptEndTime = request.getParameter("acceptEndTime");
		String countiesRegionId = request.getParameter("countiesRegionId");
		String streetRegionId = request.getParameter("streetRegionId");
		String rangeType = request.getParameter("rangeType"); //0：全部 1按户数 2按人数
		if(StringUtils.isBlank(rangeType)) {
			rangeType = "0";
		}
		
		Date from = null;
		Date to = null;
		if(StringUtils.isNotBlank(acceptStartTime)){
			from = DateUtils.getStringToDate(acceptStartTime, DateUtils.DateFormatDefault);
		}
		if(StringUtils.isNotBlank(acceptEndTime)) {
			to = DateUtils.getStringToDate(acceptEndTime, DateUtils.DateFormatDefault);
		}
		List<Region> countryRegionList = getCountryRegionList(countiesRegionId, streetRegionId);
		
		List<CompareStatResult> result = new ArrayList<CompareStatResult>();
		if(countryRegionList != null){
			result = checkBusinessStatService.getCompareStatResult(from, to, countryRegionList, rangeType);
		}
		
		model.put("rangeType", rangeType);
		model.put("resultList", result);
		model.put("countryRegionList", this.countryRegionList);
		return "/analysis/exchangeThanStatistics";
	}
	
	/**核对工作情况统计*/
	@RequestMapping("/checkWordInfoStat")
	public String checkWordInfoStat(HttpServletRequest request, ModelMap model) {
		//初始化区县列表
		this.initCountryRegionList();
		
		String acceptStartTime = request.getParameter("acceptStartTime");
		String acceptEndTime = request.getParameter("acceptEndTime");
		String countiesRegionId = request.getParameter("countiesRegionId");
		String streetRegionId = request.getParameter("streetRegionId");
		
		//调用jbpm的接口：传入受理时间区间、街道regionId；返回本区域内各个状态下的数目
		Date from = null;
		Date to = null;
		if(StringUtils.isNotBlank(acceptStartTime)){
			from = DateUtils.getStringToDate(acceptStartTime, DateUtils.DateFormatDefault);
		}
		if(StringUtils.isNotBlank(acceptEndTime)) {
			to = DateUtils.getStringToDate(acceptEndTime, DateUtils.DateFormatDefault);
		}
		String regionId = "";
		if(!StringUtils.isBlank(streetRegionId)) {
			regionId = streetRegionId;
		} else if(!StringUtils.isBlank(countiesRegionId)) {
			regionId = countiesRegionId;
		} else {
			User user = this.getLoginUser();
			regionId = "402877813833cb0c013833db09650005";
			if(user != null && user.getRegion() != null) {
				regionId = user.getRegion().getId();
			} 
						
		}
		Map<String, Map<State, Long>> resultMap = new HashMap<String,Map<State, Long>>();
		if(jbpmStatService != null){
			resultMap = jbpmStatService.countGroupByApplyStateInRegion(regionId, from, to);
		} else {
			resultMap = testJbpmStatsService.countGroupByApplyStateInRegion(regionId, from, to);
		}
		
		List<Region> countryRegionList = this.getCountryRegionList(countiesRegionId, streetRegionId);
		List<WorkInfoStatResult> result = new ArrayList<WorkInfoStatResult>();
		if(countryRegionList != null){
			for(Region region : countryRegionList) {
				if(region.getChildren() == null || region.getChildren().size() == 0){
					continue;
				}
				WorkInfoStatResult workInfoStatResult = new WorkInfoStatResult();
				workInfoStatResult.setCountryRegionName(region.getName());
				List<StreetWorkInfoData> streetWorkInfoDataList = new ArrayList<StreetWorkInfoData>();
				for(Region streetRegion : region.getChildren()) {
					StreetWorkInfoData data = new StreetWorkInfoData();
					data.setStreetRegionName(streetRegion.getName());
					Map stateMap = resultMap.get(streetRegion.getId());
					Iterator it = stateMap.keySet().iterator();
					 while(it.hasNext()) {
						 State state = (State)it.next();
						 Long value = (Long)stateMap.get(state);
						 if(state.getId().equals(Constant.ACCESS_CHECK_STATE)) {
							 data.setAccessStadardsOverStat(value);						
						 } else if(state.getId().equals(Constant.FIRST_CHECK_STATE)) {
							 data.setFirstStat(value);
						 } else if(state.getId().equals(Constant.PAUSE_CHECK_STATE)) {
							 data.setSuspendCheckStat(value);
						 } else if(state.getId().equals(Constant.TERMINAL_CHECK_STATE)) {
							 data.setTerminatCheckStat(value);
						 } else if(state.getId().equals(Constant.DIFF_STATE)) {
							 data.setGenerateDiffTableStat(value);
						 } else if(state.getId().equals(Constant.CHECK_TABLE_STATE)) {
							 data.setGenerateCheckListStat(value);
						 } else if(state.getId().equals(Constant.SECOND_CHECK_STATE)) {
							 data.setSecondCheckStat(value);
						 }
					 }
					 streetWorkInfoDataList.add(data);
				}
				workInfoStatResult.setStreetWorkInfoData(streetWorkInfoDataList);
				result.add(workInfoStatResult);
			}
			
		}		
		
		model.put("resultList", result);
		model.put("countryRegionList", this.countryRegionList);
		return "/analysis/checkInfoStatistics";
	}
	
	/**出具报告统计*/
	@RequestMapping("/reportInfoStat")
	public String reportInfoStat(HttpServletRequest request, ModelMap model) {
		//初始化区县列表
		this.initCountryRegionList();
		
		String acceptStartTime = request.getParameter("acceptStartTime");
		String acceptEndTime = request.getParameter("acceptEndTime");
		String countiesRegionId = request.getParameter("countiesRegionId");
		String streetRegionId = request.getParameter("streetRegionId");
		Date from = null;
		Date to = null;
		if(StringUtils.isNotBlank(acceptStartTime)){
			from = DateUtils.getStringToDate(acceptStartTime, DateUtils.DateFormatDefault);
		}
		if(StringUtils.isNotBlank(acceptEndTime)) {
			to = DateUtils.getStringToDate(acceptEndTime, DateUtils.DateFormatDefault);
		}
		
		String regionId = "";
		if(!StringUtils.isBlank(streetRegionId)) {
			regionId = streetRegionId;
		} else if(!StringUtils.isBlank(countiesRegionId)) {
			regionId = countiesRegionId;
		} else {
			User user = this.getLoginUser();
			regionId = "402877813833cb0c013833db09650005";
			if(user != null && user.getRegion() != null) {
				regionId = user.getRegion().getId();
			} 	
		}
		//调用jbpm的接口：传入出具报告时间区间、regionId区域Id（有可能是区县的也有可能是街镇的，如果是区县的，返回里要有街镇ID）；
		//返回本条件下出具报告总数；只超收入报告数据；只超财产报告数；收入和财产均超报告数
		Map<String, Tuple4<Long, Long, Long, Long>> resultMap = new HashMap<String, Tuple4<Long, Long, Long, Long>>();
		if(jbpmStatService != null){
			resultMap = jbpmStatService.countReportsGroupByStreetInRegion(regionId, from, to);
		} else {
			resultMap = testJbpmStatsService.countReportsGroupByStreetInRegion(regionId, from, to);
		}

		List<Region> countryRegionList = this.getCountryRegionList(countiesRegionId, streetRegionId);
		List<ReportStatResult> result = new ArrayList<ReportStatResult>();
		if(countryRegionList != null){
			for(Region region : countryRegionList) {
				if(region.getChildren() == null || region.getChildren().size() == 0){
					continue;
				}
				ReportStatResult reportStatResult = new ReportStatResult();
				reportStatResult.setCountryRegionName(region.getName());
				List<StreetReportData> streetReportDataList = new ArrayList<StreetReportData>();
				for(Region streetRegion : region.getChildren()) {
					StreetReportData data = new StreetReportData();
					data.setStreetRegionName(streetRegion.getName());
					Tuple4<Long, Long, Long, Long> reportData = resultMap.get(streetRegion.getId());
					if(reportData != null) {
						data.setReportSum(reportData._1());
						data.setSuperIncomReportNum(reportData._2());
						data.setSuperPropertyNum(reportData._3());
						data.setSuperBothNum(reportData._4());
						streetReportDataList.add(data);
					}
				}
				reportStatResult.setStreetReportDataList(streetReportDataList);
				result.add(reportStatResult);
			}
		}
		
		model.put("resultList", result);
		model.put("countryRegionList", this.countryRegionList);
		return "/analysis/reportStatistics";
	}
	
	/**导出Excel*/
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response, 
								ModelMap model) {
		List<Object> result = (List<Object>) model.get("resultList");
		StatisticsExcelUtil.exportExcel(result, "result", response);
		model.remove("resultList");
	}

}

